package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.mapper.user.AddressBookMapper;
import com.sky.pojo.AddressBook;
import com.sky.service.user.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 根据用户id所有查询地址
     * @return
     */
    @Override
    public List<AddressBook> getAllAddress() {

        return addressBookMapper.getAllAddress(BaseContext.getCurrentId());
    }

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(AddressBook.IS_DEFAULT);
        addressBookMapper.save(addressBook);
    }


    /**
     * 根据用户id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressById(Long id) {

        return addressBookMapper.getAddressById(id);
    }

    /**
     * 根据用户id修改地址
     * @param addressBook
     */
    @Override
    public void updateAddressById(AddressBook addressBook) {
        addressBookMapper.updateAddressById(addressBook);
    }


    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    public void setDefaultAddress(AddressBook addressBook) {

        //将所有地址设置成默认,因为一个userid可以有多个地址,要把这个userid的所有相关的地址状态全部修改
        //所以用userid,不是id,id只能代表一个地址
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.setDefaultAddress(addressBook);

        //再将选中的这个要修改的地址默认地址字段改为1
        addressBook.setIsDefault(1);
        addressBookMapper.updateAddressById(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }


    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        //根据userid和默认地址为1的条件去查
        AddressBook addressBook=new AddressBook();
        addressBook.setIsDefault(AddressBook.IS_DEFAULT);
        addressBook.setUserId(BaseContext.getCurrentId());
        return addressBookMapper.getDefaultAddress(addressBook);


    }
}
